package cn.xchats.onlinetraffic.common.other.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

/*
 *
 *@author teddy
 *@date 2018/4/13
 */
@SuppressWarnings("all")
@Service
public class RedisTemplateService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public void addString(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key.trim(), JSON.toJSONString(value));
    }

    public <T> T getString(String key, Type type) {
        return JSON.parseObject(String.valueOf(stringRedisTemplate.opsForValue().get(key)), type);
    }

    public void removeString(String key) {
        //stringRedisTemplate.delete(key);
    }

    public void addList(String key, Object value) {
        stringRedisTemplate.opsForList().rightPush(key.trim(), JSON.toJSONString(value));
    }

    public List getList(String key) {
        return stringRedisTemplate.opsForList().range(key.trim(), 0, -1);
    }

    public void removeList(String key, long l, String value) {
        stringRedisTemplate.opsForList().remove(key, l, value);
    }

    public void addHash(String key1, String key2, Object value) {
        stringRedisTemplate.opsForHash().put(key1.trim(), key2.trim(), JSON.toJSONString(value));
    }

    public <T> T getHash(String key1, String key2, Class type) {
        return (T) JSON.parseObject(String.valueOf(stringRedisTemplate.opsForHash().get(key1.trim(), key2.trim())), type);
    }

    public RedisTemplate getRedisTemplate() {
        return this.stringRedisTemplate;
    }

    public void removeHash(String key, String... key2) {
        stringRedisTemplate.opsForHash().delete(key, key2);
    }

    //毫秒单位
    public void setTimeOut(String key,long timeOut){
        stringRedisTemplate.expire(key,timeOut, TimeUnit.MILLISECONDS);
    }

}
